package com.rickpan.socketio;

import com.corundumstudio.socketio.SocketIOServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * Socket.IO服务器启动器
 */
@Component
public class SocketIOServerRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(SocketIOServerRunner.class);

    @Autowired
    private SocketIOServer socketIOServer;

    @Override
    public void run(String... args) throws Exception {
        try {
            socketIOServer.start();
            logger.info("🚀 Socket.IO服务器启动成功，端口: {}", socketIOServer.getConfiguration().getPort());
        } catch (Exception e) {
            logger.error("❌ Socket.IO服务器启动失败", e);
            throw e;
        }
    }

    /**
     * 应用关闭时停止Socket.IO服务器
     */
    @jakarta.annotation.PreDestroy
    public void destroy() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            logger.info("🛑 Socket.IO服务器已停止");
        }
    }
}
